package org.example.conf;

import org.kie.api.KieServices;
import org.kie.api.builder.KieBuilder;
import org.kie.api.builder.KieFileSystem;
import org.kie.api.builder.KieModule;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;
import org.kie.internal.io.ResourceFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import java.io.IOException;

@Configuration
public class DroolsConf {
    // 制定规则文件的路径
    @Value("${rule-path}")
    private String RULES;

    @Bean
    public KieContainer kieContainer() throws IOException {
        KieServices kieServices = KieServices.Factory.get();
        KieFileSystem kieFileSystem = kieServices.newKieFileSystem();
        Resource[] ruleFiles = new PathMatchingResourcePatternResolver()
//                .getResources("classpath*:" + RULES + "**/*.*");
                .getResources("classpath:rules/*.*");
        for (Resource ruleFile : ruleFiles) {
//            kieFileSystem.write(ResourceFactory.newClassPathResource(RULES + ruleFile.getFilename()));
            kieFileSystem.write(ResourceFactory.newFileResource(ruleFile.getFile()));
        }
        KieBuilder kb = kieServices.newKieBuilder(kieFileSystem);
        kb.buildAll();
        KieModule kieModule = kb.getKieModule();
        return kieServices.newKieContainer(kieModule.getReleaseId());
    }


    @Bean
    public KieSession kieSession() throws IOException {
        return kieContainer().newKieSession();
    }
}
